import { routerRedux } from "dva/router";
import moment from "moment"
import { handleUrl } from './request';
import numeral from 'numeral';
window.numeral = numeral;
//滚动到指定位置 有动画的
export function moveTo(target) {
	let scrollT = document.body.scrollTop || document.documentElement.scrollTop;
	if (scrollT > target) {
		let timer = setInterval(function () {
			let scrollT = document.body.scrollTop || document.documentElement.scrollTop;
			let step = Math.floor(-scrollT / 6);
			document.documentElement.scrollTop = document.body.scrollTop = step + scrollT;
			if (scrollT <= target) {
				document.body.scrollTop = document.documentElement.scrollTop = target;
				clearTimeout(timer);
			}
		}, 20)
	}
	else if (scrollT == 0) {
		let timer = setInterval(function () {
			let scrollT = document.body.scrollTop || document.documentElement.scrollTop;
			let step = Math.floor(300 / 3 * 0.7);
			document.documentElement.scrollTop = document.body.scrollTop = step + scrollT;
			if (scrollT >= target) {
				document.body.scrollTop = document.documentElement.scrollTop = target;
				clearTimeout(timer);
			}
		}, 20)
	}
	else if (scrollT < target) {
		let timer = setInterval(function () {
			let scrollT = document.body.scrollTop || document.documentElement.scrollTop;
			let step = Math.floor(scrollT / 6);
			document.documentElement.scrollTop = document.body.scrollTop = step + scrollT;
			if (scrollT >= target) {
				document.body.scrollTop = document.documentElement.scrollTop = target;
				clearTimeout(timer);
			}
		}, 20)
	}
	else if (target == scrollT) {
		return false;
	}
}
//滚动到指定位置 没动画的
export function goTo(target) {
	if (isNull(target)) {
		let hash = window.location.hash;
		hash = hash.substring(1);
		let historyTop = localStorage.getItem(MI_APP_CODE + "historyTop");
		if (isNull(historyTop)) {
			historyTop = {}
		}
		else {
			historyTop = JSON.parse(historyTop)
		}
		let oldPrevTop = historyTop[hash];
		if (!isNull(oldPrevTop)) {
			target = oldPrevTop
		}
		else {
			target = 0
		}
	}
	else {
		target = target * 1
	}
	setTimeout(() => {
		document.documentElement.scrollTop = target;
		document.body.scrollTop = target
	}, 100)
}
/**
 * 获取滚动条距离顶端的距离
 * @return {}支持IE6
 */
export function getScrollTop() {
	let scrollPos = document.documentElement.scrollTop || document.body.scrollTop;
	return scrollPos;
}
//取出本地存储的上个页面的信息 并且把当前页面的信息存进去
export function getPrevInfo(url) {
	let historyTop = localStorage.getItem(MI_APP_CODE + "historyTop");
	if (isNull(historyTop)) {
		historyTop = {}
	}
	else {
		historyTop = JSON.parse(historyTop)
	}
	let oldPrevTop = historyTop[url];
	let prevTop = getScrollTop();
	let hash = window.location.hash;
	hash = hash.substring(1);
	historyTop = {
		...historyTop,
		[hash]: prevTop
	};
	let keysArr = Object.keys(historyTop);
	localStorage.setItem(MI_APP_CODE + "historyTop", JSON.stringify(historyTop));
	if (!isNull(oldPrevTop)) {
		return {
			oldPrevTop: oldPrevTop
		}
	}
	return {}
}
export function goToPage({ dispatch, config, isReplace }) {
	let { url, state, open_type } = config;
	if (!isNull(url)) {
		let pathname = url;
		let search = "";
		let pIndex = url.indexOf("?");
		if (pIndex != -1) {
			pathname = url.substring(0, pIndex);
			search = url.substring(pIndex + 1)
		}
		search = encodeURI(search);
		config = {
			pathname,
			search,
			state
		};
		if (pathname.indexOf("http") != -1 || pathname.indexOf("https") != -1) {
			window.open(pathname, "_self")
		}
		else {
			pathname = pathname.toString();
			// if (pathname !== "/" && pathname.indexOf("/page") == -1 && pathname.indexOf("/create") == -1 && pathname.indexOf("/edit") == -1 && pathname.indexOf("/view") == -1 && pathname.indexOf("/map") == -1 && pathname.indexOf("/changePassword") == -1 && pathname.indexOf("/cart") == -1 && pathname.indexOf("/placeOrder") == -1 && pathname.indexOf("/addAddress") == -1) {
			// 	console.log("地址配置错误,只能为page create edit view map");
			// 	return;
			// }
			else {
				let { oldPrevTop } = getPrevInfo(url);
				setTimeout(() => {
					config = {
						...config,
						state: {
							...state,
							top: oldPrevTop
						}
					};
					let title = state && state.title;
					let urlString = location.origin + "/#" + config.pathname + "?" + config.search;
					if (browser.isInApp && open_type != 3) {//如果open_type是3  就不重新打开webview,在当前webview中新开页面
						Func.callHander(bridge, "openWindow", { "urlString": urlString, title });
					}
					else {
						// dispatch(routerRedux.replace(config))
						if (isReplace) {
							dispatch(routerRedux.replace(config))
						}
						else {
							console.log(config);
							dispatch(routerRedux.push(config))
						}
					}

				}, 1)
			}
		}
	}
	else {
		console.log("没有配置跳转地址");
	}
}
//从url中获取参数 如果没有传url 就取当前页的url
export function getParmaFromUrl(url) {
	if (!url) {
		url = window.location.href;
	}
	url = decodeURIComponent(url);
	if (url.indexOf("?") == -1) {
		return {}
	}
	let search = url.substring(url.indexOf("?") + 1, url.length);
	let serachArr = search.split("&");
	let obj = {};
	serachArr.map(function (item) {
		let itemArr = item.split("=");
		obj[itemArr[0]] = itemArr[1]
	});
	return obj
}
export function isNull(str) {
	return str === "" || str === undefined || str === null
}


export function getWindow() {
	let winWidth, winHeight;
	// 获取窗口宽度
	if (window.innerWidth) {
		winWidth = window.innerWidth;
	}
	else if ((document.body) && (document.body.clientWidth)) {
		winWidth = document.body.clientWidth;
	}
	// 获取窗口高度
	if (window.innerHeight) {
		winHeight = window.innerHeight;
	}
	else if ((document.body) && (document.body.clientHeight)) {
		winHeight = document.body.clientHeight;
	}
	// 通过深入 Document 内部对 body 进行检测，获取窗口大小
	if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
		winHeight = document.documentElement.clientHeight;
		winWidth = document.documentElement.clientWidth;
	}
	return {
		width: winWidth,
		height: winHeight
	}
}
//跳转页面时url替换{{oid}}等 obj是数据源
export function filterTemplate(str, obj) {
	obj = {
		...obj,
		"_u.username": localStorage[MI_APP_CODE + "MI_APP_CODE"],
		"_u.nickname": localStorage[MI_APP_CODE + "nickname"],
		"_u.user_id": localStorage[MI_APP_CODE + "user_id"],
		"_u.role_id": localStorage[MI_APP_CODE + "role_id"],
		"_l.token": localStorage[MI_APP_CODE + "mi_token"],
		"_platform": browser.platform,
		"_html.up_triangle": "<i style='color:#f5222d;font-size:12px;' class='anticon anticon-caret-up'><svg viewBox='0 0 1024 1024' class='' data-icon='caret-up' width='1em' height='1em' fill='currentColor' aria-hidden='true'><path d='M858.9 689L530.5 308.2c-9.4-10.9-27.5-10.9-37 0L165.1 689c-12.2 14.2-1.2 35 18.5 35h656.8c19.7 0 30.7-20.8 18.5-35z'></path></svg></i>",
		"_html.down_triangle": "<i style='color:#52c41a;font-size:12px;' class='anticon anticon-caret-down'><svg viewBox='0 0 1024 1024' class='' data-icon='caret-down' width='1em' height='1em' fill='currentColor' aria-hidden='true'><path d='M840.4 300H183.6c-19.7 0-30.7 20.8-18.5 35l328.4 380.8c9.4 10.9 27.5 10.9 37 0L858.9 335c12.2-14.2 1.2-35-18.5-35z'></path></svg></i>",
	}
	if (!str) {
		return ""
	}
	let reg = /({{)[.\w]+(}})/g;
	str = str.replace(reg, function () {
		let a = arguments[0].replace(/({{|}})/g, "");
		if (obj && obj[a] !== undefined && obj[a] !== null) {
			a = obj[a];
		}
		else {
			a = ""
		}
		return a;
	});
	return filterCalc(str);
}

window.mappingValue = function (val, obj) {
	if (isNull(obj[val])) {
		return val
	}
	return obj[val]
};
//form配置中的 data_store.fields和从url中获取的参数的过滤转类型 data_type
export function handleUrlParams(arr, obj) {
	let newObj = {};
	arr.map(item => {
		for (let i in obj) {
			let itemkey = item.name;
			if (itemkey === i) {
				let data_type = item.data_type || "string";
				let val = obj[i];
				if (data_type === "number") {
					val = Number(val)
				}
				else {
					val = val + "";
				}
				newObj[itemkey] = val
			}
		}
	});
	return newObj
}

/**
 * 下拉单选 或者单选按钮  val在list中 就返回val 否则返回""
 * @param list 选项
 * @param val 选中的值或者赋的值
 * @param key 唯一值 以此值进行匹配
 * @returns {*} 如果val在list中就返回val 否则返回""
 */
export function combineDefaultStr(list = [], val, value_datatype?, key = "code") {
	let listLen = list.length;
	let newVal = val;
	if (isNull(val)) {
		return val
	}
	if (isNull(list) || list.length == 0) {
		return undefined
	}
	if (isNull(value_datatype)) {
		newVal = val + ""
	}
	if (value_datatype === "number") {
		newVal = Number(val)
	}
	for (let i = 0; i < listLen; i++) {
		if (list[i][key] !== val && i == listLen - 1) {
			newVal = undefined;
			break;
		}
		else if (list[i][key] === val) {
			newVal = val;
			break;
		}
	}
	return newVal;
}

/**
 * group的默认值 如果不在当前请求 的数据当中 就把默认值中不存在的值删除- 适用于多选的组件
 * @param list 选项
 * @param val 选中的值或者赋的值
 * @param key 唯一值 以此值进行匹配
 * @param dataType 数据类型 string和number 默认string
 * @returns {Array} 返回数组
 */
export function combineDefaultArr(list, val, key, dataType) {
	list = list || [];
	if (!val && val !== 0 && val !== '0') {
		return []
	} else {
		if (!(val instanceof Array)) {
			val = val.toString().split(",");
		}
	}
	if (dataType) {
		let a = [];
		val.map((item, key) => {
			if (dataType == "string") {
				item = item.toString();
			}
			else if (dataType == "number") {
				item = Number(item);
			}
			a[key] = item
		});
		val = a;
	}

	let listLen = list.length;
	let valLen = val.length;
	let newVal = [];
	if (listLen > 0) {
		for (let i = 0; i < valLen; i++) {
			let isIn = false;
			for (let j = 0; j < listLen; j++) {
				if (val[i] !== list[j][key] && j == listLen - 1) {
					isIn = false;
					break;
				} else if (val[i] === list[j][key]) {
					isIn = true;
					break;
				}
			}
			if (isIn) {
				newVal.push(val[i])
			}
		}
	}
	else {
		newVal = val
	}
	return newVal;
}

//判断访问终端
let u = navigator.userAgent;
export const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

//获取几分钟前
export function getMinute(minute) {
	minute = minute || 0;
	let now = new Date();
	now = (now.valueOf() + (minute * 60 * 1000));
	return now;
}

//获取和当前时间相差的小时数的时间
export function getHour(hour) {
	hour = hour || 0;
	let now = new Date();
	now = (now.valueOf() + (hour * 3600 * 1000));
	return now;
}

//获取和当前时间相差的天数 time如果time!=1就会把时分秒设为00:00:00:00
export function getDay(day, time) {
	day = day || 0;
	let now = new Date();
	if (time != 1) {
		now.setHours(0);
		now.setMinutes(0);
		now.setSeconds(0);
		now.setMilliseconds(0)
	}
	now = (now.valueOf() + (day * 24 * 3600 * 1000));
	return now
}
//获取和当前周相差的周数的周一
export function getWeek(week, time) {
	week = week || 0;
	let now = new Date();
	if (time != 1) {
		now.setHours(0);
		now.setMinutes(0);
		now.setSeconds(0);
		now.setMilliseconds(0)
	}
	let day = now.getDay();
	day = day == 0 ? 6 : day - 1;
	now = (now.valueOf() - (-week * 7 + day) * 24 * 3600 * 1000);
	return now
}
//获取和当前月相差的月数的1号
export function getMonth(month, time) {
	month = month || 0;
	let now = new Date();
	if (time != 1) {
		now.setHours(0);
		now.setMinutes(0);
		now.setSeconds(0);
		now.setMilliseconds(0)
	}
	now.setDate(1);
	let nowMonth = now.getMonth();
	let newMonth = nowMonth + month;
	now.setMonth(newMonth);
	now = now.valueOf();
	return now;
}
//获取和当前年相差的年份的01-01
export function getYear(year, time) {
	year = year || 0;
	let now = new Date();
	if (time != 1) {
		now.setHours(0);
		now.setMinutes(0);
		now.setSeconds(0);
		now.setMilliseconds(0)
	}
	now.setMonth(0);
	now.setDate(1);
	let nowYear = now.getFullYear();
	let newYear = nowYear + year;
	now.setFullYear(newYear);
	now = now.valueOf();
	return now
}
export function handleDateFunc(str) {
	if (str.indexOf("getHour") != -1) {
		return eval(str);
	}
	if (str.indexOf("getMinute") != -1) {
		return eval(str);
	}
	if (str.indexOf("getDay") != -1) {
		return eval(str);
		str = str.replace("getDay(", "").replace(")", "");
		str = isNull(str) ? 0 : Number(str);
		return getDay(str);
	}
	if (str.indexOf("getWeek") != -1) {
		return eval(str)
		str = str.replace("getWeek(", "").replace(")", "");
		str = isNull(str) ? 0 : Number(str);
		return getWeek(str);
	}
	if (str.indexOf("getMonth") != -1) {
		return eval(str)
		str = str.replace("getMonth(", "").replace(")", "");
		str = isNull(str) ? 0 : Number(str);
		return getMonth(str);
	}
	if (str.indexOf("getYear") != -1) {
		return eval(str)
		str = str.replace("getYear(", "").replace(")", "");
		str = isNull(str) ? 0 : Number(str);
		return getYear(str);
	}
}
//时间戳是毫秒还是秒 isMsec为1时表示是毫秒 否则为秒  默认的话为毫秒(可配置)
export function timeMsec(isMsec) {
	// 有可能是 *1000  或者 /1000
	if (isNull(isMsec) || isMsec === 1 || isMsec === "1" || isMsec === true) {
		return 1
	}
	else {
		return 1000;
	}
}
//把时分秒 毫秒设为0
export function timeZero(time) {
	return time.hour(0).minute(0).second(0).millisecond(0)
}

// 添加 修改时 根据配置的data_type处理formData
export function handleDataType(controls, obj) {
	let newObj = {};
	let filterKyes = [];
	controls.map(item => {
		let itemKey = item.name;
		if (item.is_filter == 1) {
			filterKyes.push(itemKey);
		}
		let isNumber = item.data_type === "number";
		let val = obj[itemKey];
		let isDeletedKey = false;
		if ((val === undefined || (val === "" && isNumber) || val === null) && item.data_type != "jsonobject" && item.data_type != "object" && item.data_type != "hex") {
			val = null
		}
		else {
			if (item.data_type == "timestamp") {
				val = moment(val).format()
			}
			else if (item.data_type == "array") {
				val = val;
			}
			else if (item.data_type == "jsonobject" || item.data_type == "object") {
				isDeletedKey = true;
				let obj1 = {
					[itemKey]: {}
				};
				for (let i in obj) {
					if (i.toString().substring(0, itemKey.toString().length + 2) == itemKey + "->") {
						let arr = i.split("->");
						if (arr.length == 2) {
							arr.map((item, key) => {
								if (key == 0) {
									if (!obj1[arr[0]]) {
										obj1[arr[0]] = {}
									}
								}
								if (key == 1) {
									obj1[arr[0]][arr[1]] = obj[i]
								}
							})
						}
						else if (arr.length == 3) {
							arr.map((item, key) => {
								if (key == 0) {
									if (!obj1[arr[0]]) {
										obj1[arr[0]] = {}
									}
								}
								if (key == 1) {
									if (!obj1[arr[0]][arr[1]]) {
										obj1[arr[0]][arr[1]] = {}
									}
								}
								if (key == 2) {
									obj1[arr[0]][arr[1]][arr[2]] = obj[i]
								}
							})
						}
					}
				}
				if (item.data_type == "jsonobject") {
					obj1 = {
						[itemKey]: JSON.stringify(obj1[itemKey])
					}
				}
				for (let k in obj1) {
					newObj[k] = obj1[k]
				}
			}
			else if (item.data_type == "hex") {
				isDeletedKey = true;
				let { config } = item;
				let hex = "";
				config.map((i, k) => {
					let { name, length, data_type } = i;
					let value = obj[name];
					if (isNull(value)) {
						value = new Array(length).fill("0").join("");//如果值为空，就全补0
					}
					else {
						value += "";
					}
					if (value.length < length) {//长度不足 前面补0
						value = new Array(length - value.length).fill("0").join("") + value;
					}
					hex += value;
				})
				newObj[itemKey] = hex;
			}
			else {
				val = isNumber ? Number(val) : val + ""
			}
		}
		if (!isDeletedKey) {
			newObj[itemKey] = val
		}
	});
	newObj = {
		// ...obj,
		...newObj
	};
	filterKyes.map(i => {
		delete newObj[i];
	});
	for (let i in newObj) {
		if (newObj[i] === undefined) {
			newObj[i] = null
		}
	}
	return newObj;
}

export function isArrInStr(arr = [], str) {
	if (isNull(arr) || isNull(str)) {
		return false;
	}
	let isIn = false;
	arr.map(item => {
		item = "," + item + ",";
		if (str.indexOf(item) != -1) {
			isIn = true
		}
	});
	return isIn;
}
//需要动态计算的组件的属性
export const calcArr = [
	"place_holder", "label", "disabled", "visible", "required", "readonly", "tips", "title", "reg_rules"
];
export function calcField(val, obj) {
	obj = {
		...obj,
		"_u.username": localStorage[MI_APP_CODE + "username"],
		"_u.nickname": localStorage[MI_APP_CODE + "nickname"],
		"_u.user_id": localStorage[MI_APP_CODE + "user_id"],
		"_u.role_id": localStorage[MI_APP_CODE + "role_id"],
		"_platform": browser.platform,
		"_html.up_triangle": "<i style='color:#f5222d;font-size:12px;' class='anticon anticon-caret-up'><svg viewBox='0 0 1024 1024' class='' data-icon='caret-up' width='1em' height='1em' fill='currentColor' aria-hidden='true'><path d='M858.9 689L530.5 308.2c-9.4-10.9-27.5-10.9-37 0L165.1 689c-12.2 14.2-1.2 35 18.5 35h656.8c19.7 0 30.7-20.8 18.5-35z'></path></svg></i>",
		"_html.down_triangle": "<i style='color:#52c41a;font-size:12px;' class='anticon anticon-caret-down'><svg viewBox='0 0 1024 1024' class='' data-icon='caret-down' width='1em' height='1em' fill='currentColor' aria-hidden='true'><path d='M840.4 300H183.6c-19.7 0-30.7 20.8-18.5 35l328.4 380.8c9.4 10.9 27.5 10.9 37 0L858.9 335c12.2-14.2 1.2-35-18.5-35z'></path></svg></i>",
	}
	if (val === 0 || val === "0") {
		return 0;
	}
	if (isNull(val)) {
		return val;
	}
	if (typeof val === "number") {
		return val;
	}
	else if (val.toString().indexOf("{{") != -1 && val && val.toString().indexOf("}}") != -1) {
		// let isShow = eval(filterExp(val,"obj"));
		//不计算整个表达式 只把{{xx}}替换成掉
		let isShow = filterExp(val, obj);
		//$$_ xx _$$ 有$$__$$的就去计算 eval
		isShow = filterCalc(isShow);
		if (isNull(isShow)) {
			isShow = false;
		}
		if (isShow === "true") {
			return true;
		}
		if (isShow === "false") {
			return false;
		}
		return isShow;
	}
	else if (val.toString().indexOf("$$_") != -1 && val && val.toString().indexOf("_$$") != -1) {
		return filterCalc(val);
	}
	else {
		return val
	}
}
export function filterExpRules(str, data_str) {
	if (isNull(str)) {
		return str;
	}
	else if (str.toString().indexOf("{{") == -1 || str.toString().indexOf("}}") == -1) {
		return str;
	}
	let reg = /({{)[\w\-\>]+(}})/g;
	str = str.replace(reg, function () {
		let a = arguments[0].replace(/({{|}})/g, "");
		if (!isNull(data_str)) {
			a = data_str + "['" + a + "']";
		} else {
			a = "formData['" + a + "']";
		}
		return a;
	});
	console.log(str);
	return str;
}
//过滤表达式 过滤{{}}
export function filterExp(str, obj) {
	obj = {
		...obj,
		"_u.username": localStorage[MI_APP_CODE + "username"],
		"_u.nickname": localStorage[MI_APP_CODE + "nickname"],
		"_u.user_id": localStorage[MI_APP_CODE + "user_id"],
		"_u.role_id": localStorage[MI_APP_CODE + "role_id"],
		"_platform": browser.platform,
		"_html.up_triangle": "<i style='color:#f5222d;font-size:12px;' class='anticon anticon-caret-up'><svg viewBox='0 0 1024 1024' class='' data-icon='caret-up' width='1em' height='1em' fill='currentColor' aria-hidden='true'><path d='M858.9 689L530.5 308.2c-9.4-10.9-27.5-10.9-37 0L165.1 689c-12.2 14.2-1.2 35 18.5 35h656.8c19.7 0 30.7-20.8 18.5-35z'></path></svg></i>",
		"_html.down_triangle": "<i style='color:#52c41a;font-size:12px;' class='anticon anticon-caret-down'><svg viewBox='0 0 1024 1024' class='' data-icon='caret-down' width='1em' height='1em' fill='currentColor' aria-hidden='true'><path d='M840.4 300H183.6c-19.7 0-30.7 20.8-18.5 35l328.4 380.8c9.4 10.9 27.5 10.9 37 0L858.9 335c12.2-14.2 1.2-35-18.5-35z'></path></svg></i>",
	}
	if (isNull(str)) {
		return str;
	}
	else if (str.toString().indexOf("{{") == -1 || str.toString().indexOf("}}") == -1) {
		return str;
	}
	var reg = /({{)[.\w\-\>]+(}})/g;
	str = str.replace(reg, function () {
		let a = arguments[0].replace(/({{|}})/g, "");
		a = "obj['" + a + "']";
		let result = "";
		try {
			result = eval(a)
		}
		catch (e) {
			console.error(e, a, str)
		}
		return result;
	});
	if (str === "undefined" || str == "null" || isNull(str)) {
		str = undefined
	}
	return str;
}
// eval($$_   _$$)
export function filterCalc(str) {
	if (!str) {
		return ""
	}
	let reg = /(\$\$_)[^\$]*(_\$\$)/g;
	str = str.replace(reg, function () {
		let a = arguments[0].replace(/(\$\$_|_\$\$)/g, "");
		let result = "";
		try {
			result = eval(a)
		}
		catch (e) {
			console.error(e, a, str)
		}
		return result;
	});
	return str;
}

//生成4位随机数
export function MI_S4() {
	return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
//生成UUID
export function getUUID() {
	let uuid = (MI_S4() + "" + MI_S4() + "" + new Date().valueOf());
	return uuid;
}
let config = localStorage.getItem(MI_APP_CODE + "config");
try {
	config = JSON.parse(JSON.parse(config))
} catch (e) {
	config = {}
}
config = config || {};
let file_root = config.file_root;
if (isNull(file_root)) {
	file_root = "http://mc-wb.oss-cn-shanghai.aliyuncs.com/"
}
export function handleOSS(file) {
	if (!isNull(file) && file.indexOf("http") == -1 && file.indexOf("https") == -1) {
		return file_root + file
	}
	return file;
}

//权限相关函数
//本地的权限中是否有这个权限
export function checkPermission(code) {
	let permission = localStorage[MI_APP_CODE + "permissions"];
	if (!isNotNull(permission)) {
		return true;
	}
	else {
		permission = "," + permission + ",";
		code = "," + code + ",";
		return permission.indexOf(code) != -1
	}
}
//是否有计算权限的必要 ctrl code 和本地权限 都不为空
export function isCheckPer(ctrl, code) {
	return isNotNull(ctrl) && isNotNull(code) && isNotNull(localStorage[MI_APP_CODE + "permissions"])
}
//可能根据权限项判断的字段
export const calcPermissionArr = [
	"disabled", "visible", "required", "readonly"
];
export function isNotNull(value) {
	return value !== undefined && value !== "" && value !== null;
}

//下拉组件中 arr=["select1","select2"] obj={code:1,name:2}||{} select2对应name 如果field_mapping不存在或者没有对应关系，就按顺序匹配
export function handleSelect(arr, obj, field_mapping, isSelectList?) {
	obj = obj || {};
	let keyArr = [], newArr = [];
	for (let i in obj) {
		if (i != "code") {
			keyArr.push(i)
		}
	}
	arr.map((item, key) => {
		if (isSelectList) {
			newArr.push(item)
		}
		else {
			if (key !== 0) {
				newArr.push(item)
			}
		}
	});
	let newObj = {};
	newArr.map((item, key) => {
		if (!isNull(item)) {
			let newItem = obj[keyArr[key]];
			if (field_mapping && field_mapping[item]) {
				newItem = obj[field_mapping[item]]
			}
			newObj[item] = newItem
		}
	});
	return newObj;
}

//处理图片 没有http 加上img_root
export function handleImg(url) {
	if (!isNull(url) && (url.substr(0, 4) == "http" || url.substr(0, 5) == "https")) {
		return url;
	}
	let prefix = "";
	try {
		prefix = handleUrl(localStorage[MI_APP_CODE + "img_root"]);
	} catch (err) {
		console.log(err);
	}
	if (isNull(prefix)) {
		prefix = ""
	}
	return prefix + url;
}


// 解决 form表单中的输入框获取焦点时，对顶部和底部固定的两部分的影响
export function handleInputFocusBlur(isBlur?) {
	//默认为聚焦时的处理 isBlur为true时是失焦时的处理
	if (isBlur) {
		//解决微信内 输入框失去焦点时 页面无法回弹的bug
		setTimeout(() => {
			let isFocus = localStorage.isFocus;
			console.log(isFocus);
			if (browser.versions.weixin && isFocus === "false") {
				setTimeout(() => {
					window.scrollTo(0, document.body.scrollTop + 1);
					document.body.scrollTop >= 1 && window.scrollTo(0, document.body.scrollTop - 1);
				}, 10)
			}
		}, 50);

		if (document.getElementById("footerButtons")) {
			document.getElementById("footerButtons").style.position = "fixed";
			document.getElementById("footerButtons").style.bottom = "0";
		}
		if (document.getElementById("header")) {
			document.getElementById("header").style.position = "fixed";
		}
	}
	else {
		localStorage.isFocus = true;
		setTimeout(() => {
			localStorage.isFocus = false;
		}, 200);
		if (document.getElementById("footerButtons")) {
			document.getElementById("footerButtons").style.position = "relative";
			document.getElementById("footerButtons").style.bottom = "unset"
		}
		if (document.getElementById("header")) {
			document.getElementById("header").style.position = "absolute";
		}
	}
}
export function backToPrevious() {
	setTimeout(() => {
		if (browser.isInApp) {//event事件中的返回上一页
			Func.callHander(bridge, "closeWindow", {});
		}
		else {
			window.history.go(-1);
		}
	}, 100)
}
//
export function loginCallbackToken(e) {
	let { app, token, user, permissions, menus, isLoading } = e;
	console.log("mi_token-componentDidMount", token);
	if (browser.versions.android) {
		app = JSON.parse(app);
		user = JSON.parse(user);
		localStorage[MI_APP_CODE + "menus"] = menus;
	}
	else {
		localStorage[MI_APP_CODE + "menus"] = JSON.stringify(menus);
	}
	localStorage[MI_APP_CODE + "mi_token"] = token;
	localStorage[MI_APP_CODE + 'permissions'] = permissions;
	let { role_id, user_id, nikname, username } = user;
	for (let i in user) {
		localStorage[MI_APP_CODE + i] = user[i];
	}
	for (let i in app) {
		if (i == "img_root" || i == "name") {
			localStorage[MI_APP_CODE + i] = app[i];
		}
		localStorage[MI_APP_CODE + "config"] = app.config_json;
	}
	if (isLoading !== 0) {
		setTimeout(() => {
			window.location.reload();
		}, 100)
	}
}

// 弹窗选择联系人 多选 等弹窗的高度配置
export const getMDrawerFullHeight = "85%";


// 配置input_width min_width时 处理成百分比或者是px
export function handlePx(str) {
	if (isNull(str)) {
		return str;
	}
	if (!isNaN(str)) {
		return str + "px"
	}
	return str;
}

export function loadScript(src) {
	return new Promise((resolve, reject) => {
		const script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = src;
		script.onload = resolve;
		script.onerror = reject;
		document.head.appendChild(script);
	});
}
export function isString(str) {
	return (typeof str == 'string') && str.constructor == String;
}
//表达式处理
export function filterCalcField(item, expressions) {
	if (isNotNull(expressions) && expressions.length > 0) {
		try {
			for (var val of expressions) {

				var temp_data = eval(val.expression);
				if (isString(temp_data)) {
					temp_data = temp_data.replace(/`/g, "'");
				}
				item[val.field] = temp_data;

			}
		} catch (err) {
			console.log(err);
		}
	}
	return item;
}
